//
//  PBAccountDetailController.m
//  PBHomeDemo
//
//  Created by Playboy on 2018/5/30.
//  Copyright © 2018年 tmkj. All rights reserved.
//

#import "PBAccountDetailController.h"
#import "PBAccountDetailCell.h"
#import "PBAccountListModel.h"
#import "PBAccountEmptyView.h"
#import "PBPayNowController.h"

static NSString * const kPBAccountDetailCell = @"PBAccountDetailCell";

@interface PBAccountDetailController ()<UITableViewDelegate,UITableViewDataSource,PBAccountDetailCellDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *desLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UIButton *rentButton;
@property (weak, nonatomic) IBOutlet UIButton *lifeButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *centerXConstraint;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *allSelectButton;
@property (weak, nonatomic) IBOutlet UILabel *sumLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (nonatomic, strong) NSMutableArray    *dataSource;
@property (nonatomic, assign) BOOL isLife;
@property (nonatomic, strong) PBAccountEmptyView  *emptyView;
@property (nonatomic, assign) NSInteger page;

@end

@implementation PBAccountDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
}

- (void)configure {
    [self configureData];
    [self configureView];
}
- (void)configureData {
    self.page = 1;
    NSDictionary *param = @{@"currentPage":@"1",@"pageSize":@"10",@"houseId":self.houseId};
    [TMNetwork requestPostWithParam:param url:@"/bill/query" callback:^(TMBaseReqModel *model) {
        [self.tableView.mj_header endRefreshing];
        if (model.code == 200) {
            [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.data[@"houseBase"][@"cover"]] placeholderImage:nil];
            self.nameLabel.text = model.data[@"houseBase"][@"name"];
            if ([model.data[@"houseBase"][@"unitNum"] integerValue] == 0) {
                // 没有单元
                self.desLabel.text = [NSString stringWithFormat:@"%@居室%@栋%@楼%@号",model.data[@"houseBase"][@"roomNum"],model.data[@"houseBase"][@"buildingNum"],model.data[@"houseBase"][@"floor"],model.data[@"houseBase"][@"houseNum"]];
            }else {
                self.desLabel.text = [NSString stringWithFormat:@"%@居室%@单元%@栋%@楼%@号",model.data[@"houseBase"][@"roomNum"],model.data[@"houseBase"][@"unitNum"],model.data[@"houseBase"][@"buildingNum"],model.data[@"houseBase"][@"floor"],model.data[@"houseBase"][@"houseNum"]];
            }
            self.typeLabel.text = model.data[@"houseBase"][@"rentPayment"];
            self.dataSource = [PBAccountListModel objectArrayWithKeyValuesArray:model.data[@"bills"]];
            [self.tableView reloadData];
            if (self.dataSource.count < 10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
            if (self.dataSource.count == 0) {
                [self.tableView addSubview:self.emptyView];
                self.bottomView.hidden = YES;
            }else {
                [self.emptyView removeFromSuperview];
                self.bottomView.hidden = NO;
            }
        }else {
            [self showHint:model.message];
        }
    }];
}
- (void)configureMoreData {
    NSDictionary *param = @{@"currentPage":[NSString stringWithFormat:@"%zd",self.page],@"pageSize":@"10",@"houseId":self.houseId};
    [TMNetwork requestPostWithParam:param url:@"/bill/query" callback:^(TMBaseReqModel *model) {
        [self.tableView.mj_footer endRefreshing];
        if (model.code == 200) {
            NSArray *array = [PBAccountListModel objectArrayWithKeyValuesArray:model.data[@"bills"]];
            if (array.count < 10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
            [self.dataSource addObject:array];
            [self.tableView reloadData];
        }else {
            [self showHint:model.message];
        }
    }];
}
- (void)configureView {
    [self.tableView registerNib:[UINib nibWithNibName:kPBAccountDetailCell bundle:nil] forCellReuseIdentifier:kPBAccountDetailCell];
    [TMRefreshHelper headerRefresh:self.tableView withTarget:self action:@selector(headerRefreshMethod)];
    [TMRefreshHelper footerRefresh:self.tableView withTarget:self action:@selector(footerRefreshMethod)];
}

- (void)headerRefreshMethod {
    if (self.isLife) {
        [self loadLifeData];
    }else {
        [self configureData];
    }
}

- (void)footerRefreshMethod {
    self.page += 1;
    if (self.isLife) {
        [self loadMoreLifeData];
    }else {
        [self configureMoreData];
    }
}

- (void)loadLifeData {
    self.page = 1;
    NSDictionary *param = @{@"currentPage":@"1",@"pageSize":@"10",@"houseId":self.houseId};
    [TMNetwork requestPostWithParam:param url:@"/bill/queryLife" callback:^(TMBaseReqModel *model) {
        [self.tableView.mj_header endRefreshing];
        if (model.code == 200) {
            self.dataSource = [PBAccountListModel objectArrayWithKeyValuesArray:model.data[@"bills"]];
            [self.tableView reloadData];
            if (self.dataSource.count < 10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
            if (self.dataSource.count == 0) {
                [self.tableView addSubview:self.emptyView];
                self.bottomView.hidden = YES;
            }else {
                [self.emptyView removeFromSuperview];
                self.bottomView.hidden = NO;
            }
        }else {
            [self showHint:model.message];
        }
    }];
}
- (void)loadMoreLifeData {
    NSDictionary *param = @{@"currentPage":[NSString stringWithFormat:@"%zd",self.page],@"pageSize":@"10",@"houseId":self.houseId};
    [TMNetwork requestPostWithParam:param url:@"/bill/queryLife" callback:^(TMBaseReqModel *model) {
        [self.tableView.mj_footer endRefreshing];
        if (model.code == 200) {
            NSArray *array = [PBAccountListModel objectArrayWithKeyValuesArray:model.data[@"bills"]];
            if (array.count < 10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
            [self.dataSource addObject:array];
            [self.tableView reloadData];
        }else {
            [self showHint:model.message];
        }
    }];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PBAccountDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBAccountDetailCell forIndexPath:indexPath];
    cell.delegate = self;
    [cell refreshWithArray:self.dataSource indexPath:indexPath isLife:self.isLife];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    view.backgroundColor = UIColorWithRGB(242, 242, 242);
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PBAccountDetailCell *cell = (PBAccountDetailCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell selectMethodClick:cell.selectButton];
}


#pragma mark - PBAccountDetailCellDelegate
- (void)addMoney:(NSString *)money {
    NSString *last = self.sumLabel.text;
    CGFloat sum = [last floatValue] + [money floatValue];
    self.sumLabel.text = [NSString stringWithFormat:@"%.2f",sum];
}

- (void)reduceMoney:(NSString *)money {
    NSString *last = self.sumLabel.text;
    CGFloat sum = [last floatValue] - [money floatValue];
    self.sumLabel.text = [NSString stringWithFormat:@"%.2f",sum];
}

- (void)clearMoney {
    self.sumLabel.text = @"0";
}

- (void)allSelected {
    self.allSelectButton.selected = YES;
}

- (void)notAllSelected {
    self.allSelectButton.selected = NO;
}



#pragma mark - click
// 全选
- (IBAction)allSelctButtonClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if (sender.selected) {
       // 全选
        for (NSInteger i = 0; i < self.dataSource.count; i ++) {
            PBAccountListModel *model = self.dataSource[i];
            if (!model.isSelected) {
                [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
            }
        }
    }else {
        // 取消全选
        for (NSInteger i = 0; i < self.dataSource.count; i ++) {
            [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
        }
    }
}

// 租金账单
- (IBAction)rentButtonClick:(UIButton *)sender {
    self.centerXConstraint.constant = 0;
    [self.rentButton setTitleColor:UIColorWithRGB(243, 159, 13) forState:UIControlStateNormal];
    [self.lifeButton setTitleColor:UIColorWithRGB(102,102,102) forState:UIControlStateNormal];
    self.isLife = NO;
    self.allSelectButton.selected = NO;
    [self configureData];
}

// 生活账单
- (IBAction)lifeButtonClick:(UIButton *)sender {
    self.centerXConstraint.constant = kScreenWidth/2;
    [self.rentButton setTitleColor:UIColorWithRGB(102,102,102) forState:UIControlStateNormal];
    [self.lifeButton setTitleColor:UIColorWithRGB(243, 159, 13) forState:UIControlStateNormal];
    self.isLife = YES;
    self.allSelectButton.selected = NO;
    [self loadLifeData];
}

// 立即支付
- (IBAction)payButtonClick:(UIButton *)sender {
    if ([self.sumLabel.text floatValue] == 0) {
        [self showHint:@"请先选择账单"];
        return;
    }
    NSMutableArray *arrayM = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.dataSource.count; i ++) {
        PBAccountListModel *model = self.dataSource[i];
        NSMutableDictionary *dicM = [[NSMutableDictionary alloc] init];
        if (model.isSelected) {
            [dicM setObject:model.ID forKey:@"billId"];
            [arrayM addObject:dicM];
        }
    }

    [TMNetwork requestPostWithParam:arrayM url:@"/order/createBills" callback:^(TMBaseReqModel *model) {
        if (model.code == 200) {
            PBPayTypeModel *pay = [[PBPayTypeModel alloc] init];
            pay.price = self.sumLabel.text;
            PBPayNowController *vc = [[PBPayNowController alloc] init];
            vc.code = model.data;
            vc.payModel = pay;
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            [self showHint:model.message];
        }
    }];
    
}
#pragma mark - super
- (void)resetNavigationBarItems {
    [super resetNavigationBarItems];
    self.title = @"账单详情";
}

- (PBAccountEmptyView *)emptyView {
    if (!_emptyView) {
        _emptyView = [PBAccountEmptyView emptyView];
        _emptyView.frame = self.tableView.frame;
    }
    return _emptyView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
